<template>
	<view class="canvas-wheel-container">
		<canvas 
			class="wheel-canvas" 
			canvas-id="lotteryWheel"
			:style="{ width: canvasSize + 'px', height: canvasSize + 'px' }"
			@touchstart="onTouchStart"
			@touchmove="onTouchMove"
			@touchend="onTouchEnd"
		></canvas>
		<view class="pointer" @click="startLottery">
			<view class="pointer-btn">
				<text class="pointer-text">{{ isRotating ? '抽奖中...' : '开始抽奖' }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'LotteryWheelCanvas',
		props: {
			prizeList: {
				type: Array,
				default: () => []
			},
			canvasSize: {
				type: Number,
				default: 300
			}
		},
		data() {
			return {
				ctx: null,
				centerX: 0,
				centerY: 0,
				radius: 0,
				isRotating: false,
				currentAngle: 0,
				targetAngle: 0,
				animationId: null
			}
		},
		mounted() {
			this.initCanvas();
		},
		watch: {
			prizeList: {
				handler(newVal) {
					console.log('奖品列表更新:', newVal);
					if (this.ctx && newVal.length > 0) {
						this.drawWheel();
					}
				},
				deep: true
			}
		},
		methods: {
			// 初始化Canvas
			initCanvas() {
				console.log('开始初始化Canvas');
				const query = uni.createSelectorQuery().in(this);
				query.select('.wheel-canvas')
					.fields({ node: true, size: true })
					.exec((res) => {
						console.log('Canvas查询结果:', res);
						if (res && res[0] && res[0].node) {
							const canvas = res[0].node;
							const ctx = canvas.getContext('2d');
							
							if (!ctx) {
								console.error('无法获取Canvas上下文');
								return;
							}
							
							// 设置canvas尺寸
							const dpr = uni.getSystemInfoSync().pixelRatio;
							canvas.width = this.canvasSize * dpr;
							canvas.height = this.canvasSize * dpr;
							ctx.scale(dpr, dpr);
							
							this.ctx = ctx;
							this.centerX = this.canvasSize / 2;
							this.centerY = this.canvasSize / 2;
							this.radius = this.canvasSize / 2 - 20;
							
							console.log('Canvas初始化完成，开始绘制');
							this.drawWheel();
						} else {
							console.error('Canvas节点未找到');
							// 延迟重试
							setTimeout(() => {
								this.initCanvas();
							}, 100);
						}
					});
			},
			
			// 绘制转盘
			drawWheel() {
				if (!this.ctx) {
					console.error('Canvas上下文不存在');
					return;
				}
				
				console.log('开始绘制转盘，奖品数量:', this.prizeList.length);
				
				const ctx = this.ctx;
				const itemCount = this.prizeList.length;
				
				if (itemCount === 0) {
					console.warn('奖品列表为空');
					return;
				}
				
				const angleStep = (2 * Math.PI) / itemCount;
				
				// 清空画布
				ctx.clearRect(0, 0, this.canvasSize, this.canvasSize);
				
				// 绘制背景圆
				ctx.beginPath();
				ctx.arc(this.centerX, this.centerY, this.radius, 0, 2 * Math.PI);
				ctx.fillStyle = '#f5f5f5';
				ctx.fill();
				
				// 绘制扇形区域
				this.prizeList.forEach((prize, index) => {
					const startAngle = index * angleStep + this.currentAngle;
					const endAngle = (index + 1) * angleStep + this.currentAngle;
					
					// 扇形颜色
					const colors = ['#FF6B6B', '#4ECDC4', '#FFD93D', '#6BCF7F', '#A8E6CF', '#FF8B94'];
					const color = colors[index % colors.length];
					
					console.log(`绘制扇形 ${index}: ${prize.name}, 颜色: ${color}, 角度: ${startAngle} - ${endAngle}`);
					
					// 绘制扇形
					ctx.beginPath();
					ctx.moveTo(this.centerX, this.centerY);
					ctx.arc(this.centerX, this.centerY, this.radius, startAngle, endAngle);
					ctx.closePath();
					ctx.fillStyle = color;
					ctx.fill();
					
					// 绘制边框
					ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
					ctx.lineWidth = 2;
					ctx.stroke();
					
					// 绘制文字
					this.drawText(prize.name, startAngle + angleStep / 2, index);
				});
				
				// 绘制中心圆
				ctx.beginPath();
				ctx.arc(this.centerX, this.centerY, 30, 0, 2 * Math.PI);
				ctx.fillStyle = '#FFD700';
				ctx.fill();
				ctx.strokeStyle = '#FFA500';
				ctx.lineWidth = 3;
				ctx.stroke();
				
				console.log('转盘绘制完成');
			},
			
			// 绘制文字
			drawText(text, angle, index) {
				const ctx = this.ctx;
				const textRadius = this.radius * 0.7;
				const x = this.centerX + textRadius * Math.cos(angle);
				const y = this.centerY + textRadius * Math.sin(angle);
				
				ctx.save();
				ctx.translate(x, y);
				ctx.rotate(angle + Math.PI / 2);
				
				// 设置文字样式
				ctx.fillStyle = '#FFFFFF';
				ctx.font = 'bold 12px Arial';
				ctx.textAlign = 'center';
				ctx.textBaseline = 'middle';
				
				// 绘制文字背景
				ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
				const textWidth = ctx.measureText(text).width;
				ctx.fillRect(-textWidth/2 - 2, -8, textWidth + 4, 16);
				
				// 绘制文字
				ctx.fillStyle = '#FFFFFF';
				ctx.fillText(text, 0, 0);
				
				ctx.restore();
			},
			
			// 开始抽奖
			startLottery() {
				if (this.isRotating) return;
				
				this.isRotating = true;
				
				// 随机选择奖品
				const selectedPrize = this.selectRandomPrize();
				const prizeIndex = this.prizeList.findIndex(item => item.id === selectedPrize.id);
				
				// 计算目标角度
				const itemCount = this.prizeList.length;
				const angleStep = 360 / itemCount;
				const targetAngle = 360 - (prizeIndex * angleStep + angleStep / 2);
				
				// 多转几圈再停到目标位置
				const circles = 5;
				this.targetAngle = circles * 360 + targetAngle;
				
				// 开始动画
				this.animateWheel();
			},
			
			// 动画转盘
			animateWheel() {
				const duration = 3000; // 3秒
				const startTime = Date.now();
				const startAngle = this.currentAngle;
				const angleDiff = this.targetAngle - startAngle;
				
				const animate = () => {
					const elapsed = Date.now() - startTime;
					const progress = Math.min(elapsed / duration, 1);
					
					// 使用缓动函数
					const easeOut = 1 - Math.pow(1 - progress, 3);
					
					this.currentAngle = startAngle + angleDiff * easeOut;
					this.drawWheel();
					
					if (progress < 1) {
						this.animationId = requestAnimationFrame(animate);
					} else {
						this.isRotating = false;
						this.$emit('lottery-complete', this.prizeList[this.getCurrentPrizeIndex()]);
					}
				};
				
				animate();
			},
			
			// 获取当前指向的奖品索引
			getCurrentPrizeIndex() {
				const itemCount = this.prizeList.length;
				const angleStep = 360 / itemCount;
				const normalizedAngle = (360 - this.currentAngle) % 360;
				return Math.floor(normalizedAngle / angleStep);
			},
			
			// 随机选择奖品
			selectRandomPrize() {
				const random = Math.random();
				let cumulativeProbability = 0;
				
				for (let prize of this.prizeList) {
					cumulativeProbability += prize.probability;
					if (random <= cumulativeProbability) {
						return prize;
					}
				}
				
				return this.prizeList[0];
			},
			
			// 触摸事件
			onTouchStart(e) {
				// 可以添加触摸交互
			},
			
			onTouchMove(e) {
				// 可以添加触摸交互
			},
			
			onTouchEnd(e) {
				// 可以添加触摸交互
			}
		}
	}
</script>

<style scoped>
	.canvas-wheel-container {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.wheel-canvas {
		border-radius: 50%;
		box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.3);
	}
	
	.pointer {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10;
	}
	
	.pointer-btn {
		width: 120rpx;
		height: 120rpx;
		background: linear-gradient(45deg, #FFD700, #FFA500);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.3);
		cursor: pointer;
	}
	
	.pointer-text {
		color: #fff;
		font-size: 24rpx;
		font-weight: bold;
	}
</style> 